#include <stdio.h>
#include "usb_device_uac.h"
#include "esp_log.h"
#include "esp_err.h"
#include "driver/i2s.h"
#include "driver/gpio.h"
static const char *TAG = "usb_uac_main";
void i2s_init() {
    i2s_config_t i2s_cfg = {
        .mode = I2S_MODE_MASTER | I2S_MODE_TX,
        .sample_rate = 48000,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
        .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
        .communication_format = I2S_COMM_FORMAT_STAND_I2S,
        .dma_buf_count = 20,
        .dma_buf_len = 1024,
        .use_apll = false,  // 高精度时钟
        .tx_desc_auto_clear = true,

    };
    i2s_pin_config_t pin_cfg = {
        .bck_io_num = GPIO_NUM_39,
        .ws_io_num = GPIO_NUM_40,
        .data_out_num = GPIO_NUM_38,
        .data_in_num = I2S_PIN_NO_CHANGE
    };
    ESP_ERROR_CHECK(i2s_driver_install(I2S_NUM_0, &i2s_cfg, 0, NULL));
    ESP_ERROR_CHECK(i2s_set_pin(I2S_NUM_0, &pin_cfg));
}

void play_audio(const uint8_t* data, size_t len) {
    size_t bytes_written = 0;
    i2s_write(I2S_NUM_0, data, len, &bytes_written, portMAX_DELAY);
    if (bytes_written < len) {
        ESP_LOGE(TAG, "Audio underflow!");
    }
}




static esp_err_t uac_device_output_cb(uint8_t *buf, size_t len, void *arg)
{
    // size_t bytes_written = 0;
    // bsp_extra_i2s_write(buf, len, &bytes_written, 0);

    play_audio(buf, len);

    return ESP_OK;
}

static esp_err_t uac_device_input_cb(uint8_t *buf, size_t len, size_t *bytes_read, void *arg)
{
    // if (bsp_extra_i2s_read(buf, len, bytes_read, 0) != ESP_OK) {
    //     ESP_LOGE(TAG, "i2s read failed");
    // }
    return ESP_OK;
}

static void uac_device_set_mute_cb(uint32_t mute, void *arg)
{
    // ESP_LOGI(TAG, "uac_device_set_mute_cb: %"PRIu32"", mute);
    // bsp_extra_codec_mute_set(mute);
}

static void uac_device_set_volume_cb(uint32_t volume, void *arg)
{
    // ESP_LOGI(TAG, "uac_device_set_volume_cb: %"PRIu32"", volume);
    // bsp_extra_codec_volume_set(volume, NULL);
}

void app_main(void)
{
    i2s_init();
    uac_device_config_t config = {
        .output_cb = uac_device_output_cb,          // Speaker output callback
        .input_cb = uac_device_input_cb,            // Microphone input callback
        .set_mute_cb = uac_device_set_mute_cb,      // Set mute callback
        .set_volume_cb = uac_device_set_volume_cb,  // Set volume callback
        .cb_ctx = NULL,
    };
    uac_device_init(&config);
}
